import React, { useCallback, useEffect, useRef, useState } from "react";
import { Button, Upload } from "antd";
import "./index.less";
import SparkMD5 from "spark-md5";
import Child from "./Child";

type propsTypes = {};

function Test(props: propsTypes) {
  const domRef = useRef<HTMLDivElement | null>(null);
  const worker = useRef<any>(null);
  let [count, setCount] = useState(0);
  let [childCount, setChildCount] = useState({
    name: "123",
    age: {
      a: "8910",
    },
  });
  useEffect(() => {
    worker.current = new Worker(new URL("./worker.js", import.meta.url));

    init();
    return () => {
      worker.current.terminate();
    };
  }, []);
  const init = () => {
    const observer = new IntersectionObserver((entrys) => {
      if (entrys[0].isIntersecting) {
        // console.log("-------执行代码逻辑");
      }
    });
    observer.observe(domRef.current as HTMLDivElement);
  };
  //自定义处理文件
  const handleUploadChange = (files: any) => {
    console.log(files, "-----files");
  };
  const customRequest = async (event: any) => {
    // console.log(event, "------event");

    const { file, onSuccess } = event;
    const startTime = performance.now();
    worker.current.postMessage({
      type: "upload",
      data: file,
    });

    worker.current.onmessage = (e: any) => {
      console.log(e.data, "------worker 计算hash值");
    };
    // const chunks: any = await createChunks(file, 1000); //拿到分片
    // const hash = await fileHash(chunks);
    // console.log(hash, "-----正常计算");

    const endTime = performance.now();

    console.log(`这段逻辑运行用了${endTime - startTime}`);

    onSuccess();
  };
  //计算hash值
  const fileHash = (chunks: any) => {
    return new Promise((resolve, reject) => {
      const spark = new SparkMD5();
      function _read(i: number) {
        if (i >= chunks.length) {
          resolve(spark.end());
          return;
        }
        const blob = chunks[i];
        const reader = new FileReader();
        reader.onload = (e: any) => {
          const bytes = e.target.result;
          spark.append(bytes);
          _read(i + 1);
        };

        reader.readAsArrayBuffer(blob);
      }
      _read(0);
    });
  };
  const onChange = useCallback(() => {
    console.log("---一个普通的函数");
  }, []);
  //分片函数
  const createChunks = (file: Blob, chunkSize: number) => {
    const result = [];
    for (let i = 0; i < file.size; i += chunkSize) {
      result.push(file.slice(i, i + chunkSize));
    }
    return result;
  };
  return (
    <div className="flex flex-row gap-3">
      <div>
        <div className="text-lg">intersectionObserve</div>
        <div className="box">
          <div className="box_child1"></div>
          <div className="box_child2" ref={domRef}></div>
        </div>
      </div>
      <div className="text-lg">webWorker</div>
      <Upload customRequest={customRequest} accept="*" directory={true}>
        <Button onChange={handleUploadChange}>上传</Button>
      </Upload>
      <Button onClick={() => setCount(++count)}>父亲的按钮</Button>
      <div>{"父亲自己的数字---》" + count}</div>
      <Child
        text={"这是一段来自父亲的文字"}
        onChange={onChange}
        setChildCount={setChildCount}
        childCount={childCount}
      />
    </div>
  );
}

export default Test;
